package com.dz.risk.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dz.risk.common.SysConstant;
import com.dz.risk.common.utils.ResponseUtils;
import com.dz.risk.dao.ProprietaryHoldingBondInformationDao;
import com.dz.risk.pojo.QueryParams;
import com.dz.risk.pojo.domain.ProprietaryHoldingBondInformationEntity;
import com.dz.risk.pojo.domain.ProprietaryValuationOfBondHoldingsInformationEntity;
import com.dz.risk.pojo.domain.ReportFormsEntity;
import com.dz.risk.service.ProprietaryHoldingBondInformationService;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;


@Service("proprietaryHoldingBondInformationService")
public class ProprietaryHoldingBondInformationServiceImpl extends ServiceImpl<ProprietaryHoldingBondInformationDao, ProprietaryHoldingBondInformationEntity> implements ProprietaryHoldingBondInformationService {
    @Autowired
    private ProprietaryHoldingBondInformationDao proprietaryHoldingBondInformationDao;

    @Override
    public IPage<ProprietaryHoldingBondInformationEntity> query(QueryParams queryParams) {
        IPage<ProprietaryHoldingBondInformationEntity> page = new Page<>();
        page.setCurrent(queryParams.getPageNum());
        page.setSize(queryParams.getPageSize());
        QueryWrapper<ProprietaryHoldingBondInformationEntity> wrapper = new QueryWrapper<ProprietaryHoldingBondInformationEntity>();

        wrapper.lambda()
                .eq(!StringUtils.isEmpty(queryParams.getInitDate()),ProprietaryHoldingBondInformationEntity::getInitDate, queryParams.getInitDate())
                .eq(!StringUtils.isEmpty(queryParams.getStockCode()),ProprietaryHoldingBondInformationEntity::getStockCode, queryParams.getStockCode())
                .like(!StringUtils.isEmpty(queryParams.getPaperTitles()),ProprietaryHoldingBondInformationEntity::getPaperTitles, queryParams.getPaperTitles())
                .orderByDesc(ProprietaryHoldingBondInformationEntity::getInitDate);
        IPage<ProprietaryHoldingBondInformationEntity> entityIPage = proprietaryHoldingBondInformationDao.selectPage(page, wrapper);
        return entityIPage;
    }

    @Override
    public ProprietaryHoldingBondInformationEntity queryByBondCode(String bondCode) {
        QueryWrapper<ProprietaryHoldingBondInformationEntity> wrapper = new QueryWrapper<ProprietaryHoldingBondInformationEntity>();

        if (StringUtils.hasLength(bondCode) && !String.valueOf(SysConstant.ZERO).equals(bondCode)) {
            wrapper.eq("stock_code", bondCode).orderByDesc("stock_code");
        }
        return proprietaryHoldingBondInformationDao.selectOne(wrapper);
    }

    @Override
    public List<ProprietaryHoldingBondInformationEntity> queryByVersion(Long version) {
        QueryWrapper<ProprietaryHoldingBondInformationEntity> wrapper = new QueryWrapper<ProprietaryHoldingBondInformationEntity>();
        wrapper.lambda().eq(ProprietaryHoldingBondInformationEntity::getInitDate, version);
        return proprietaryHoldingBondInformationDao.selectList(wrapper);
    }

    @Override
    public void doExport(HttpServletResponse response, QueryParams queryParams) throws IOException {
        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sh = wb.createSheet();
        /*
            "日期","部门","市场名称","证券代码","证券名称","投资类型","证券类别","债券类型","年利率","开始计息日","到期日","剩余月份","面值","市值","自由券数量","买断数量","质押数量","债券评级","派息日期","派息金额","债券数量","银行间代码","评级","债卷隐含评级","剩余未还本金","未来30天兑付金额","借贷质押数量","付息方式","累计利息"
         */
        String[] titles = {"日期","部门","市场名称","证券代码","证券名称","投资类型","证券类别","债券类型","年利率","开始计息日","到期日","剩余月份","面值","市值","自由券数量","买断数量","质押数量","债券评级","派息日期","派息金额","债券数量","银行间代码","评级","债卷隐含评级","剩余未还本金","未来30天兑付金额","借贷质押数量","付息方式","累计利息"};
        Row row = sh.createRow(0);
        CellStyle style = wb.createCellStyle();
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);

        // 第一行设置标题
        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            Cell cell1 = row.createCell(i);
            cell1.setCellValue(title);
            cell1.setCellStyle(style);
            //设置单元格大小
            sh.setColumnWidth(i, 6000);
        }

        IPage<ProprietaryHoldingBondInformationEntity> page = new Page<>();
        page.setCurrent(queryParams.getPageNum());
        page.setSize(queryParams.getPageSize());
        QueryWrapper<ProprietaryHoldingBondInformationEntity> wrapper = new QueryWrapper<ProprietaryHoldingBondInformationEntity>();
        if (queryParams.getInitDate().contains("-")){
            queryParams.setInitDate(queryParams.getInitDate().replace("-",""));
        }
        wrapper.lambda()
                .eq(!StringUtils.isEmpty(queryParams.getInitDate()),ProprietaryHoldingBondInformationEntity::getInitDate, queryParams.getInitDate())
                .eq(!StringUtils.isEmpty(queryParams.getStockCode()),ProprietaryHoldingBondInformationEntity::getStockCode, queryParams.getStockCode())
                .like(!StringUtils.isEmpty(queryParams.getPaperTitles()),ProprietaryHoldingBondInformationEntity::getPaperTitles, queryParams.getPaperTitles())
                .orderByDesc(ProprietaryHoldingBondInformationEntity::getInitDate);
        List<ProprietaryHoldingBondInformationEntity> proprietaryHoldingBondInformationEntities = proprietaryHoldingBondInformationDao.selectList(wrapper);
        final String fileName = "自营估值债券持仓信息_%s.xlsx";
        ServletOutputStream outputStream = ResponseUtils.getOutputStreamAndSettingFileFormat(response, fileName);
        //如果该版本得风险因子回溯有数据则填充进Excel
        if (!CollectionUtils.isEmpty(proprietaryHoldingBondInformationEntities)) {
            Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams(), ProprietaryHoldingBondInformationEntity.class, proprietaryHoldingBondInformationEntities);
            sheets.write(outputStream);
            outputStream.close();
            sheets.close();
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        wb.write(response.getOutputStream());
        wb.close();
    }
}